//
//  ImageListCollectionView.swift
//  photoTool
//
//  Created by 刘清元 on 2022/8/27.
//

import UIKit
import Photos
import WCDBSwift
class ImageListCollectionView: UICollectionView,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

    private var cellItemDidSelectedBlock:((_ indexPath:IndexPath)->())?
    ///设置点击事件
    @objc func cellItemDidSelected(_ closure:@escaping (_ indexPath:IndexPath)->Void){
        cellItemDidSelectedBlock = closure
    }
    public var cellValue = UserDefaults.standard.value(forKey: "cellValue") as! Int
    
    public var listArr:[(title:String,list:[ImageModel])] = []{
        didSet{
            reloadData()
        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        delegate = self
        dataSource = self
        register(UINib.init(nibName: "ImageCollectionViewCell", bundle: Bundle.main), forCellWithReuseIdentifier: "cell")
        register(UINib.init(nibName: "ImageListCollectionHeaderReusableView", bundle: Bundle.main), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
        register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footer")
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        listArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        listArr[section].list.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ImageCollectionViewCell
        let model = listArr[indexPath.section].list[indexPath.row]
        let assetResult = PHAsset.fetchAssets(withLocalIdentifiers: [model.localIdentifier!], options: nil)
        if let asset = assetResult.firstObject{
            let options = PHImageRequestOptions.init()
            options.isSynchronous = true
            options.resizeMode = .fast
            PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: 100, height: model.height!*100/model.width!), contentMode: .aspectFill, options: options) { image, info in
                cell.contentImg.image = image
            }
        }
        if traitCollection.userInterfaceIdiom == .phone {
            cell.nameLab.text = model.name
        }else{
            cell.nameLab.text = "width:\(model.width ?? 0),height:\(model.height ?? 0)\nsize:\(model.fileSize ?? 0)\n\(model.name ?? "")"
            cell.labelConstaintHeight.constant = 60
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if traitCollection.userInterfaceIdiom == .phone{
            let itemWidth = (screenW-10)/3
            return CGSize(width: itemWidth, height: itemWidth)
        }else{
            
            return CGSize(width: 20*cellValue, height: 60*cellValue)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if listArr[section].title.isEmpty{
            return CGSize(width: screenW, height: 0);
        }else{
            return CGSize(width: screenW, height: 40);
        }
    }
 
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        .zero
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header", for: indexPath) as! ImageListCollectionHeaderReusableView
            header.titleLab.text = listArr[indexPath.section].title
            return header
        }else{
            let footer = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footer", for: indexPath)
            return footer
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        5
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        5
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        .zero
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if cellItemDidSelectedBlock != nil {
            cellItemDidSelectedBlock!(indexPath)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
        UIContextMenuConfiguration.init(identifier: nil) {
            let VC = ImageDetailViewController.init()
            VC.imageModel = self.listArr[indexPath.section].list[indexPath.row]
            VC.preferredContentSize = CGSize(width: 280, height: 360)
           return VC
        } actionProvider: { elements in
            let model = self.listArr[indexPath.section].list[indexPath.row]
//            let deleteAction = UIAction.init(title: "删除", image: UIImage.init(systemName: "trash"),attributes: [.destructive], state: .off, handler: { action in
//                // 删除
//                let localIdentifier = model.localIdentifier
//                PHPhotoLibrary.shared().performChanges {
//                    let assetResult = PHAsset.fetchAssets(withLocalIdentifiers: [localIdentifier!], options: nil)
//                        PHAssetChangeRequest.deleteAssets(assetResult)
//                } completionHandler: { result, error in
//                    print(error?.localizedDescription ?? "")
//                }
//            })
            let infoAction = UIAction.init(title: "大小：\(model.fileSize ?? 0)", image: UIImage.init(systemName: "info.circle"), state: .off) { action in
                
            }
            if #available(iOS 15.0, *) {
                return UIMenu.init(title: model.name!, subtitle: "大小：\(model.fileSize ?? 0)", children: [infoAction])
            } else {
                // Fallback on earlier versions
                return UIMenu.init(title: model.name!, children: [infoAction])
            }
        }
    }
}
